<template>
  <div class="manualinput">
    <div class="content-box">

      <div class="swiper-btngroup flex flex-jus-between">
        <img src="../assets/icon-left.svg" @click="prev">
        <div>共{{ totalPage }}张,第{{ nowPage }}张</div>
        <img src="../assets/icon-right.svg" @click="next">
      </div>

      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="item in invoiceList" :key="item.index">
              <div class="invoicetype flex">
                <img src="../assets/icon-yz.svg" alt="" srcset="">
                <div>{{ item.type }}</div>
              </div>
              <dl>
                <dt>
                  <p>发票信息</p>
                  <p>CNY : <span style="color:black;">{{ item.fare }}</span></p>
                </dt>
                <dd v-for="v in item.records" :key="v.index"  v-if="!v.children">
                  <div class="input-group flex flex-jus-start">
                    <div>{{ v.label }}</div>
                    <input type="text" inputmode="number" v-model="v.value" readonly>
                  </div>
                </dd>
                <dd style="padding-left: 0;">
                  <dl v-for="v in item.records" :key="v.index" v-if="v.children">
                    <dt style="font-weight: bold;color:#000;">{{ v.label }}</dt>
                    <dd v-for="w in v.children">
                      <dl>
                        <dd v-for="x in w.items" :key="x.index" style="padding-left:.2rem;padding-right: 0;">
                          <!-- <dt style="font-weight: bold;color:#000;"></dt> -->
                          <div class="input-group flex flex-jus-start">
                            <div>{{ x.label }}</div>
                            <input type="text" inputmode="number" v-model="x.value" readonly>
                          </div>
                        </dd>
                      </dl>
                    </dd>
                  </dl>
                </dd>
              </dl>
              
          </div>
        </div>
        <div class="swiper-pagination"></div>
      </div>
    </div>
    <div class="btn-group flex">
      <div class="btn-edit flex" @click="edit">编辑</div>
      <div class="btn-submit flex" @click="submit">确认并添加至发票夹</div>
    </div>
    
  </div>
</template>

<script>

import swiper from "swiper"
import "swiper/swiper-bundle.css"
import { addTicket } from "../plugins/api"
import { Toast } from "vant-green"
import { mapMutations } from "vuex"
export default {
  name: 'manualInputView',
  data(){
    return {
      invoiceList : [], // 发票列表
      mySwiper    : undefined,
      totalPage   : 1,
      nowPage     : 1
    }
  },
  components: {},
  watch: {
    // 监听slides数组的变化，重新初始化Swiper
    invoiceList: function() {
      this.destroySwiper();
      this.$nextTick(() => {
        this.initSwiper("watch");
      });
    }
  },
  methods:{
    ...mapMutations(['setFullLoading','setSwiperPage']),
    toLink(url,params={}){
      this.$router.push({ path: url, query: params });
    },
    prev(){
      this.mySwiper.slidePrev();
    },
    next(){
      this.mySwiper.slideNext();
    },
    edit(){
      // 传递当前编辑的数据
      this.toLink("/manualshowedit",{index:this.nowPage-1})
    },
    submit(){
      this.$store.commit('setFullLoading',true)

      // 添加到发票夹
      // 从vuex中获取参数
      let obj = {}
      let vuexDatas = this.$store.state.tempInvoiceInputList
      obj = vuexDatas[this.nowPage - 1] // 索引
      obj['userId'] = localStorage.getItem('userId')
      obj['op']     = 'invoice'
      obj['ftype']  = 0
      obj['index']  = 1
      // 数据转换
      obj['data'] = {}
      obj['records'].map(v=>{
        if(v.children){
          let arr = []
          for(let i = 0;i < v.children.length;i++){
            arr.push({})
          }
          //二级数组
          v.children.map((w,i)=>{
            w.items.map(x=>{
              arr[i][x.key] = x.value
            })
            // arr[0][w.key] = w.value
          })
          obj['data'][v.key] = arr
        }else{
          obj['data'][v.key] = v.value
          if(['fare','totalAmount','Amount'].includes(obj['data'][v.key])){
            obj['data'][v.key] = obj.fare
          }
        }
      })
      function checkObject(o){
        for(let key in o){
          // console.log(o,o[key]);
          // 如果不是必填则直接返回true
          if(!o[key]['value'] && o[key]['required']){
            console.log("必填项未填写:",o);
            return false;
          }
        }
        return true
      }
      // 检查对象中的属性值是否全部为真
      let result = true; // 默认为true 
          result = checkObject(obj['data']); // 如果有未填写的则会返回false
      console.log("result:",result); 
      if(!result){
        this.$store.commit('setFullLoading',false)
        Toast('有必填项没有填写!')
        return false;
      }

      console.log('添加至发票夹:',obj);

      addTicket({...obj}).then(res=>{
        // console.log('添加到发票夹以后需要在vuex中和本页面删除这一条数据!',res);
        this.$store.commit('setFullLoading',false)
        if(res.code == 200){
          Toast("添加成功!")
          setTimeout(()=>{
            let arr = [...vuexDatas]
                arr.splice(this.nowPage - 1,1)
            this.$store.commit('setTempInvoiceInputList',arr)
            this.invoiceList.splice(this.nowPage-1,1)

            // 如果移除以后没有其他可编辑的发票 则跳转到列表页
            if(this.$store.state.tempInvoiceInputList.length <= 0){
              this.$router.push('/invoicelist')
            }
          },1500)
        }else{
          Toast(res.msg)
        }
      }).catch(error=>{
        console.log(error);
        this.$store.commit('setFullLoading',false)
        Toast(error.errMsg)
      })
    },
    initSwiper() {
      // 有多少张发票
      this.totalPage = this.invoiceList.length
      let _this = this
      this.nowPage = 1; // 给一个默认页码
      let page = 0
      if(this.$store.state.swiperPage != -1){
        page = this.$store.state.swiperPage
      }
      this.mySwiper = new swiper('.swiper-container', {
        initialSlide: page * 1, // 默认第一页为0
        autoHeight: true,       // 高度随内容变化
        on: {
          slideChangeTransitionStart: function(swiper){
            _this.nowPage = swiper.activeIndex + 1
            console.log(_this.nowPage);
          },
        },
      })
      this.$store.commit('setSwiperPage',-1)
    },
    destroySwiper() {
      if (this.mySwiper) {
        this.mySwiper.destroy();
      }
    }
  },
  mounted(){
    this.$store.commit('setFullLoading',false)
    // 接收参数
    this.invoiceList = [...this.$store.state.tempInvoiceInputList]
    console.log("this.invoiceList::",this.invoiceList);
    // 把总额提取到根位置
    this.invoiceList.map(v=>{
      v.records.map(w=>{
        if(['fare','totalAmount','Amount'].includes(w.key)){
          v.fare = w.value
        }
      })
      console.log("所有数据输出:",v);
    })
  },
  //设置title的钩子
  beforeRouteEnter(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
  beforeRouteUpdate(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
}
</script>
<style scoped>

.content-box {
  background-color: white;
  box-shadow: 0 0.05rem 0.15rem rgba(0, 0, 0, 0.1);
  border-radius: 0.1rem;
  margin:0.25rem;
}
dl {
  font-size: 0.3rem;
}
dl dt,
dl dd {
  color:#777;
  border-bottom: 0.01rem solid #ededed;
  padding:0.15rem 0.25rem;
  line-height: 1.7;
}
dl dd:last-child {
  border-bottom: none;
}
/* dl dd {
  line-height: 2.2;
} */
.input-group div {
  width: 2.2rem;
}
.input-group input {
  text-align: right;
  outline: none;
  border:none;
  -webkit-appearance: none;
  appearance: none;
  font-size: .3rem;
  line-height: 1;
  flex: 1;
  padding:0.15rem 0;
}
.input-group input::-webkit-input-placeholder {
  color:#ccc;
}
.red {
  color:#FF5F4E;
}
.btn-group {
  width:7.5rem;
  position: fixed;
  left:50%;
  bottom:0;
  z-index: 99;
  transform: translateX(-50%);
  padding:.2rem 0.5rem;
  background-color: white;
  box-shadow: 0 0 0.15rem rgba(0, 0, 0, 0.15);
}
.btn-submit {
  flex: 1;
  height:.8rem;
  border-radius: 100rem;
  border:none;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: #4273D9;
  color:white;
  font-size: .3rem;
}
.btn-edit {
  width:1.5rem;
  height:.8rem;
  border-radius: 100rem;
  border:1px solid #4273D9;
  color:#4273D9;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: white;
  font-size: .3rem;
  margin-right: .25rem;
}
.swiper-btngroup {
  font-size: .28rem;
  padding:.2rem .4rem;
  letter-spacing: 0.05rem;
  border-bottom: 1px dotted #eee;
}
.swiper-btngroup img {
  display: block;
  width:.25rem
}
.swiper-container {
  width: 100%;
  overflow: hidden;
}
.swiper-container .swiper-slide {
  font-size: .3rem;
  padding:0.25rem;
}
.invoicetype {
  margin:0 auto;
  width: 2rem;
  height:1.5rem;
  position: relative;
  overflow-y: hidden;
}
.invoicetype div {
  font-size: .26rem;
  color:#E03353;
}
.invoicetype img {
  width: 100%;
  position: absolute;
  left:0;
  top:-0.25rem;
}
</style>